import * as THREE from 'three'
import createThreeApp from '../../core'

function createBoxGeometry (dom: HTMLElement) {
  const { camera, scene, update, gui } = createThreeApp(dom)
  // 设置相机位置，不设置会在(0, 0, 0)位置
  camera.position.z = 100
  camera.lookAt(scene.position)

  const mesh = createBoxFromGeometry()
  mesh.position.set(-30, 0, 0)
  scene.add(mesh)



  const bufferMesh = createBoxFromBufferGeometry()
  bufferMesh.position.set(30, 0, 0)
  scene.add(bufferMesh)

  const geometry = new THREE.BoxBufferGeometry(30, 20, 20)
  const material = new THREE.MeshBasicMaterial({ color: 0xff0000, polygonOffset: true, polygonOffsetUnits: 4 })
  const mesh1 = new THREE.Mesh(geometry, material)
  mesh1.position.set(-30, 0, 0)
  scene.add(mesh1)

  // 设置网格对象的动画效果
  update((time: number) => {
    // const angle = time / 2000
    // mesh.rotation.set(angle, angle, 0)
    // bufferMesh.rotation.set(angle, angle, 0)
  })

  function updateMeshs () {
    generateGeometry(mesh)
    generateGeometry(bufferMesh)
  }

  gui.add(data, 'width', 0, 30).onChange(updateMeshs)
  gui.add(data, 'height', 0, 30).onChange(updateMeshs)
  gui.add(data, 'depth', 0, 30).onChange(updateMeshs)
  gui.add(data, 'widthSegments', 1, 10, 1).onChange(updateMeshs)
  gui.add(data, 'heightSegments', 1, 10, 1).onChange(updateMeshs)
  gui.add(data, 'depthSegments', 1, 10, 1).onChange(updateMeshs)
}

const data = {
  width: 20,
  height: 20,
  depth: 20,
  widthSegments: 1,
  heightSegments: 1,
  depthSegments: 1
}

function createBoxFromGeometry () {
  const { width, height, depth, widthSegments, heightSegments, depthSegments } = data
  // 创建一个正方体的几何体
  const geometry = new THREE.BoxGeometry(width, height, depth, widthSegments, heightSegments, depthSegments)
  // 设置他的材质
  const material = new THREE.MeshNormalMaterial()
  // 将几何体跟材质生成网格对象
  const mesh = new THREE.Mesh(geometry, material)
  return mesh
}

function createBoxFromBufferGeometry () {
  const { width, height, depth, widthSegments, heightSegments, depthSegments } = data
  const geometry = new THREE.BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments)
  const material = new THREE.MeshNormalMaterial()
  const mesh = new THREE.Mesh(geometry, material)
  return mesh
}

function generateGeometry (mesh: THREE.Mesh) {
  const { width, height, depth, widthSegments, heightSegments, depthSegments } = data
  const geometry = new THREE.BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments)
  mesh.geometry.dispose()
  mesh.geometry = geometry
}

export {
  createBoxGeometry
}

